class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def isCousins(self, root, x, y):
        """
        :type root: TreeNode
        :type x: int
        :type y: int
        :rtype: bool
        """
        d = {}
        p = {}
        if root.val == x or root.val == y:
            return False

        def search(node, val, k):
            if node.left:
                if node.left.val == val:
                    d[val] = node
                    p[val] = k + 1
                else:
                    search(node.left, val, k + 1)
            if node.right:
                if node.right.val == val:
                    d[val] = node
                    p[val] = k + 1
                else:
                    search(node.right, val, k + 1)

        search(root, x, 0)
        search(root, y, 0)
        return d[x] != d[y] and p[x] == p[y]
